﻿using YYFStructrueSearchSDK.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace YYFStructrueSearchSDK
{
    public class SearchHelper
    {
        private string access_token = "";
        private ChemStructureSearchConfig config;
        private HttpHelper HH;
        public SearchHelper(ChemStructureSearchConfig _config)
        {
            config = _config;
            if (_config != null && !string.IsNullOrWhiteSpace(_config.CachedAccessToken))
            {
                access_token = _config.CachedAccessToken;
            }
            HH = new HttpHelper();
        }
        public string GetToken(out string message)
        {
            message = "";

            if (string.IsNullOrWhiteSpace(access_token))
            {
                try
                {
                    var url = config.ApiUrl + "/api/get_access_token?appkey=" + config.AppId + "&secret=" + config.AppSecret;

                    var ret = HH.Get(url);

                    if (ret.data != null && ret.data["token"] != null && ret.data["token"].ToString() != "")
                    {
                        access_token = ret.data["token"].ToString();
                    }
                    message = ret.message;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }

            return access_token;
        }

        public ChemStructureSearchResultDto Search(ChemStructureSearchRequestDto requestdto)
        {

            ChemStructureSearchResultDto result = new ChemStructureSearchResultDto();
            var tokenmessage = "";
            var token = GetToken(out tokenmessage);
            if (!string.IsNullOrWhiteSpace(token))
            {
                var reqjo = JObject.FromObject(requestdto);
                if (requestdto.searchType == ChemStructureSearchTypeEnum.none)
                {
                    reqjo["searchType"] = "";
                }
                else
                {
                    reqjo["searchType"] = requestdto.searchType.ToString();
                }

                var body = reqjo.ToString();
                var ret = HH.Post(config.ApiUrl + "/api/search", body, token);
                try
                {
                    if (ret.data != null)
                    {
                        JObject rjo = ret.data;
                        if (rjo["hits"] != null)
                        {
                            result.Items = new List<ChemStructureSearchResultItem>();
                            result.Items = rjo.SelectToken("records").ToObject<List<ChemStructureSearchResultItem>>();
                            result.OrignalItems = rjo.SelectToken("records").ToObject<List<dynamic>>();
                            result.Total = int.Parse(rjo.SelectToken("hits") + "");
                            result.Page = requestdto.page;
                            result.PSize = requestdto.psize;

                            var TotalPages = result.Total / result.PSize;

                            if (result.Total % result.PSize > 0)
                                TotalPages++;
                            result.PageCount = TotalPages;
                            result.Success = true;
                        }
                        else
                        {
                            result.Success = false;
                            result.Message = ret.message + ";token:" + access_token;
                        }
                    }


                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Message = ex.Message + ";token:" + token;
                }
            }
            else
            {
                result.Success = false;
                result.Message = "token 获取失败:" + tokenmessage + ";token:" + token;
            }

            return result;
        }

        public ChemStructureSaveResult Save(ChemStructureSaveDto input)
        {

            ChemStructureSaveResult result = new ChemStructureSaveResult();
            var tokenmessage = "";
            var token = GetToken(out tokenmessage);
            if (!string.IsNullOrWhiteSpace(token))
            {
                var body = JObject.FromObject(new
                {
                    items = input.Items
                }).ToString();
                var ret = HH.Post(config.ApiUrl + "/api/structure/save", body, token);


                try
                {
                    result = ret.data.ToObject<ChemStructureSaveResult>();
                }
                catch (Exception ex)
                {
                    result.success = false;
                    result.message = ex.Message + ";token:" + token;
                }
            }
            else
            {
                result.success = false;
                result.message = "token 获取失败:" + tokenmessage + ";token:" + token;
            }

            return result;
        }

        public ChemStructureDeleteResult Delete(ChemStructureDeleteDto input)
        {
            ChemStructureDeleteResult result = new ChemStructureDeleteResult();
            var tokenmessage = "";
            var token = GetToken(out tokenmessage);
            if (!string.IsNullOrWhiteSpace(token))
            {

                var body = JObject.FromObject(new
                {
                    pkids = input.pkids
                }).ToString();
                var ret = HH.Post(config.ApiUrl + "/api/structure/delete", body, token);
                try
                {
                    result = ret.data.ToObject<ChemStructureDeleteResult>();
                }
                catch (Exception ex)
                {
                    result.success = false;
                    result.message = ex.Message + ";token:" + token;
                }
            }
            else
            {
                result.success = false;
                result.message = "token 获取失败:" + tokenmessage + ";token:" + token;
            }

            return result;
        }
    }
}
